// ----------------------
// 核心通信框架 (cross-tab-comm.js)
// ----------------------
class CrossTabComm {
  constructor(origin) {
    this.eventBus = new Map(); // 事件总线
    this.pendingRequests = new Map(); // Promise化请求管理
    this.origin = origin; // 安全校验域名
    
    window.addEventListener('message', (e) => {
      if (e.origin !== this.origin) return; // 安全校验
      
      const { type, data, reqId } = e.data;
      if (type === 'event') {
        // 事件总线处理
        const handlers = this.eventBus.get(data.eventType) || [];
        handlers.forEach(handler => handler(data.payload));
      } else if (type === 'response') {
        // Promise请求响应
        const resolver = this.pendingRequests.get(reqId);
        resolver?.(data);
        this.pendingRequests.delete(reqId);
      }
    });
  }

  // 事件监听
  on(eventType, handler) {
    const handlers = this.eventBus.get(eventType) || [];
    handlers.push(handler);
    this.eventBus.set(eventType, handlers);
  }

  // 发送事件
  emit(eventType, payload, targetWindow) {
    targetWindow.postMessage({
      type: 'event',
      data: { eventType, payload }
    }, this.origin);
  }

  // Promise化请求
  request(action, params, targetWindow) {
    return new Promise((resolve) => {
      const reqId = Date.now() + Math.random().toString(36).substr(2, 5);
      this.pendingRequests.set(reqId, resolve);
      
      targetWindow.postMessage({
        type: 'request',
        data: { action, params },
        reqId
      }, this.origin);
    });
  }
}

// ----------------------
// 应用场景：统一登录态管理
// ----------------------
// 主应用窗口 (https://app.example.com)
const mainAppComm = new CrossTabComm('https://app.example.com');

// 打开子窗口
const childWindow = window.open('https://service.example.com/auth');

// 监听登录事件
mainAppComm.on('USER_LOGIN', (userData) => {
  console.log('[主应用] 收到登录凭证:', userData);
  localStorage.setItem('token', userData.token);
});

// ----------------------
// 子应用窗口 - 登录服务 (https://service.example.com/auth)
// ----------------------
const authComm = new CrossTabComm('https://app.example.com');

// 模拟登录成功后同步状态
function handleLoginSuccess(user) {
  const payload = {
    token: 'jwt_token_123',
    profile: { name: user.name }
  };
  
  // 广播登录事件到所有关联窗口
  authComm.emit('USER_LOGIN', payload, window.opener);
  
  // Promise化请求示例
  authComm.request('SYNC_USER_DATA', payload, window.opener)
    .then(confirmation => {
      console.log('数据同步确认:', confirmation);
    });
}

// ----------------------
// 其他业务窗口自动同步
// ----------------------
const otherTabComm = new CrossTabComm('https://app.example.com');

otherTabComm.on('USER_LOGIN', (userData) => {
  console.log('[其他Tab] 自动更新本地登录态');
  localStorage.setItem('token', userData.token);
  updateUI(userData.profile);
});